<template>
  <div class="document-list">
    <div class="page-header">
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索文档..."
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-select v-model="fileType" placeholder="文件类型" clearable>
          <el-option label="全部" value="" />
          <el-option label="文档" value="DOC" />
          <el-option label="图片" value="IMG" />
          <el-option label="视频" value="VIDEO" />
          <el-option label="其他" value="OTHER" />
        </el-select>
        
        <el-select v-model="sortBy" placeholder="排序方式">
          <el-option label="上传时间" value="upload_time" />
          <el-option label="文件大小" value="size" />
          <el-option label="下载次数" value="downloads" />
        </el-select>
        
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
      </div>
      
      <el-button type="primary" @click="handleUpload">
        <el-icon><Upload /></el-icon>
        上传文档
      </el-button>
    </div>

    <el-card class="file-list">
      <el-table
        v-loading="loading"
        :data="documents"
        style="width: 100%"
        @row-click="handlePreview"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column label="文件名" min-width="200">
          <template #default="{ row }">
            <div class="file-name">
              <el-icon :size="20" class="file-icon">
                <component :is="getFileIcon(row.type)" />
              </el-icon>
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTagType(row.type)">{{ row.type }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="size" label="大小" width="120">
          <template #default="{ row }">
            {{ formatFileSize(row.size) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="upload_time" label="上传时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.upload_time) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="downloads" label="下载次数" width="100" />
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                :icon="Download"
                @click.stop="handleDownload(row)"
              >
                下载
              </el-button>
              <el-button
                type="danger"
                :icon="Delete"
                @click.stop="handleDelete(row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="文件预览"
      width="80%"
      class="preview-dialog"
    >
      <div class="preview-content">
        <div class="preview-header">
          <h3>{{ currentFile?.name }}</h3>
          <p>上传时间：{{ formatDate(currentFile?.upload_time) }}</p>
        </div>
        
        <div class="preview-body">
          <!-- 根据文件类型显示不同的预览内容 -->
          <template v-if="currentFile?.type === 'IMG'">
            <el-image
              :src="currentFile.url"
              fit="contain"
              :preview-src-list="[currentFile.url]"
            />
          </template>
          
          <template v-else-if="currentFile?.type === 'VIDEO'">
            <video
              :src="currentFile.url"
              controls
              style="width: 100%; max-height: 600px"
            />
          </template>
          
          <template v-else>
            <div class="document-preview">
              <iframe
                v-if="currentFile?.url"
                :src="currentFile.url"
                frameborder="0"
                style="width: 100%; height: 600px"
              />
              <div v-else class="no-preview">
                <el-icon :size="48"><Document /></el-icon>
                <p>暂不支持该类型文件的预览</p>
              </div>
            </div>
          </template>
        </div>
        
        <div class="preview-footer">
          <el-button-group>
            <el-button
              type="primary"
              :icon="Download"
              @click="handleDownload(currentFile)"
            >
              下载
            </el-button>
            <el-button
              type="info"
              :icon="Share"
              @click="handleShare(currentFile)"
            >
              分享
            </el-button>
          </el-button-group>
        </div>
      </div>
    </el-dialog>

    <!-- 分享对话框 -->
    <el-dialog
      v-model="shareVisible"
      title="分享文件"
      width="400px"
    >
      <div class="share-content">
        <el-input
          v-model="shareLink"
          readonly
          class="share-link"
        >
          <template #append>
            <el-button @click="copyShareLink">复制</el-button>
          </template>
        </el-input>
        
        <div class="share-options">
          <el-checkbox v-model="shareWithPassword">设置密码</el-checkbox>
          <el-input
            v-if="shareWithPassword"
            v-model="sharePassword"
            placeholder="请输入分享密码"
            show-password
          />
          
          <el-select v-model="shareExpireTime" placeholder="有效期">
            <el-option label="1天" value="1" />
            <el-option label="7天" value="7" />
            <el-option label="30天" value="30" />
            <el-option label="永久" value="-1" />
          </el-select>
        </div>
        
        <div class="share-qrcode">
          <qrcode-vue :value="shareLink" :size="200" level="H" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Document,
  Image as ImageIcon,
  VideoCamera,
  Files,
  Download,
  Delete,
  Share,
  Upload
} from '@element-plus/icons-vue'
import QrcodeVue from 'qrcode.vue'
import axios from 'axios'

const router = useRouter()

// 状态
const loading = ref(false)
const searchQuery = ref('')
const fileType = ref('')
const sortBy = ref('upload_time')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const documents = ref([])
const previewVisible = ref(false)
const currentFile = ref(null)
const shareVisible = ref(false)
const shareLink = ref('')
const shareWithPassword = ref(false)
const sharePassword = ref('')
const shareExpireTime = ref('7')

// 获取文件列表
const fetchDocuments = async () => {
  try {
    loading.value = true
    const response = await axios.get('/api/documents/', {
      params: {
        page: currentPage.value,
        page_size: pageSize.value,
        search: searchQuery.value,
        type: fileType.value,
        sort_by: sortBy.value
      }
    })
    documents.value = response.data.results
    total.value = response.data.count
  } catch (error) {
    ElMessage.error('获取文档列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchDocuments()
}

// 处理上传
const handleUpload = () => {
  router.push('/documents/upload')
}

// 处理预览
const handlePreview = (row) => {
  currentFile.value = row
  previewVisible.value = true
}

// 处理下载
const handleDownload = async (file) => {
  try {
    const response = await axios.get(`/api/documents/${file.id}/download/`, {
      responseType: 'blob'
    })
    
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', file.name)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('下载成功')
  } catch (error) {
    ElMessage.error('下载失败')
  }
}

// 处理删除
const handleDelete = (file) => {
  ElMessageBox.confirm(
    '确定要删除该文件吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await axios.delete(`/api/documents/${file.id}/`)
      ElMessage.success('删除成功')
      fetchDocuments()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 处理分享
const handleShare = async (file) => {
  try {
    const response = await axios.post(`/api/documents/${file.id}/share/`, {
      password: shareWithPassword.value ? sharePassword.value : null,
      expire_days: parseInt(shareExpireTime.value)
    })
    shareLink.value = response.data.share_link
    shareVisible.value = true
  } catch (error) {
    ElMessage.error('生成分享链接失败')
  }
}

// 复制分享链接
const copyShareLink = () => {
  navigator.clipboard.writeText(shareLink.value)
    .then(() => ElMessage.success('复制成功'))
    .catch(() => ElMessage.error('复制失败'))
}

// 工具函数
const getFileIcon = (type) => {
  const icons = {
    DOC: Document,
    IMG: ImageIcon,
    VIDEO: VideoCamera,
    OTHER: Files
  }
  return icons[type] || Files
}

const getTagType = (type) => {
  const types = {
    DOC: '',
    IMG: 'success',
    VIDEO: 'warning',
    OTHER: 'info'
  }
  return types[type] || 'info'
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchDocuments()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchDocuments()
}

// 初始化
fetchDocuments()
</script>

<style scoped>
.document-list {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
}

.search-bar {
  display: flex;
  gap: 12px;
  flex: 1;
}

.search-input {
  max-width: 300px;
}

.file-list {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.file-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-icon {
  color: var(--el-color-primary);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 预览对话框样式 */
.preview-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
  }
}

.preview-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.preview-header {
  padding: 20px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  
  h3 {
    margin: 0;
    font-size: 18px;
  }
  
  p {
    margin: 8px 0 0;
    color: var(--el-text-color-secondary);
    font-size: 14px;
  }
}

.preview-body {
  padding: 20px;
  min-height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: var(--el-bg-color-page);
}

.no-preview {
  text-align: center;
  color: var(--el-text-color-secondary);
  
  .el-icon {
    margin-bottom: 16px;
  }
}

.preview-footer {
  padding: 20px;
  border-top: 1px solid var(--el-border-color-lighter);
  display: flex;
  justify-content: flex-end;
}

/* 分享对话框样式 */
.share-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.share-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.share-qrcode {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: white;
  border-radius: 4px;
}

/* 动画效果 */
.el-table__row {
  transition: all 0.3s ease;
  cursor: pointer;
}

.el-table__row:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 深色模式适配 */
:deep(.dark) {
  .preview-body {
    background: var(--el-bg-color);
  }
  
  .share-qrcode {
    background: var(--el-bg-color);
  }
}
</style> 